<template>
    <div>
      <a-checkbox
        v-model:checked="checkAll"
        :indeterminate="indeterminate"
        @change="onCheckAllChange"
        @click.stop
      >
        全选
      </a-checkbox>
      <a-divider />
      <a-checkbox-group v-model:value="checkedList" @change="onCheckChange">
        <a-row>
          <a-col :span="8" v-for="item in options" :key="item">
            <a-checkbox :value="item" @click.stop>{{ item }}</a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
      <a-button @click="selectItems(['Apple', 'Orange'])">Select Apple and Orange</a-button>
    </div>
  </template>
  
  <script setup>
  import { ref, watch } from 'vue';
  
  const options = ['Apple', 'Pear', 'Orange'];
  const checkedList = ref([]);
  const previousCheckedList = ref([]);
  const checkAll = ref(false);
  const indeterminate = ref(false);
  
  const onCheckAllChange = (e) => {
    checkedList.value = e.target.checked ? [...options] : [];
    indeterminate.value = false;
  };
  
  const onCheckChange = (checkedValues) => {
    const addedValues = checkedValues.filter(item => !previousCheckedList.value.includes(item));
    const removedValues = previousCheckedList.value.filter(item => !checkedValues.includes(item));
    
    if (addedValues.length > 0) {
      console.log('Selected:', addedValues);
    }
    if (removedValues.length > 0) {
      console.log('Deselected:', removedValues);
    }
  
    previousCheckedList.value = [...checkedValues];
  };
  
  const selectItems = (items) => {
    checkedList.value = items;
  };
  
  watch(checkedList, (newValue) => {
    const length = newValue.length;
    checkAll.value = length === options.length;
    indeterminate.value = length > 0 && length < options.length;
  }, { immediate: true });
  </script>
  
  <style scoped>
  a-checkbox-group {
    display: block;
  }
  
  a-row {
    margin-bottom: 10px;
  }
  
  a-col {
    display: flex;
    align-items: center;
  }
  </style>
  